/*
 * Copyright 2011 CyberSMS.ru
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ru.cybersms.model.request;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.LinkedList;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 *
 * @author Андрей Шерцингер <support@cybersms.ru>
 */
public class SimpleHttpProcessor implements RequestProcessor {

    private String url;
    private HttpClient httpClient;
    private ResponseHandler<String> responseHandler;

    public void init(String url) throws Exception {
        this.url = url;
        this.httpClient = new DefaultHttpClient();
        if (this.url.startsWith("https")) {
            try {
                SSLContext sslContext = SSLContext.getInstance(SSLSocketFactory.TLS);
                X509TrustManager x509TrustManager = new X509TrustManager() {

                    @Override
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                sslContext.init(null, new TrustManager[]{x509TrustManager}, null);
                this.httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, new SSLSocketFactory(sslContext)));
            } catch (KeyManagementException e) {
                throw new ExceptionInInitializerError(e);
            } catch (NoSuchAlgorithmException e) {
                throw new ExceptionInInitializerError(e);
            }
        }
        this.responseHandler = new BasicResponseHandler();
    }

    @Override
    public String process(String action, Map<String, String> params) throws Exception {
        final LinkedList<NameValuePair> nameValuePairs = new LinkedList<NameValuePair>();
        final HttpPost httpPost = new HttpPost(this.url + action);
        for (String p : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(p, params.get(p)));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
        //System.out.println("REQUEST:" + nameValuePairs.toString());
        String body = httpClient.execute(httpPost, responseHandler);
        //System.out.println("BODY:" + body);
        return body;
    }
}
